<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>快递管理 - Express</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="x-ua-compatible" content="ie=edge">

  <link rel="stylesheet" th:href="@{/assets/css/bootstrap.min.css}" href="../../static/assets/css/bootstrap.min.css"/>
  <link rel="stylesheet" th:href="@{/assets/css/bootstrap-table.css}" href="../../static/assets/css/bootstrap-table.css"/>
  <link rel="stylesheet" th:href="@{/assets/css/express.css}" href="../../static/assets/css/express.css"/>
</head>
<body>
<div class="container-fluid">
  <!-- 头部 -->
  <nav th:replace="admin/module/nav::html"></nav>
  <!-- 主体 -->
  <div class="row">
    <!-- 左侧菜单 -->
    <div th:replace="admin/module/sidebar::html"></div>
    <div class="col-md-10">
      <!-- 筛选条件 -->
      <div class="panel-heading">
        <form class="form-inline">
          <div class="form-group">
            <label for="inputOrderStatus">快递状态</label>
            <select id="inputOrderStatus" class="form-control">
              <option value=-1>所有状态</option>
              <option value=1>待入库</option>
              <option value=2>已入库</option>
              <option value=3>出库派送</option>
              <option value=4>用户已收件</option>
            </select>
          </div>
          <div class="form-group">
            <label for="inputStartDate" class="ml10">起</label>
            <input type="date" id="inputStartDate" class="form-control ml10">
            <label for="inputEndDate" class="ml10">讫</label>
            <input type="date" id="inputEndDate" class="form-control ml10">
          </div>
          <div class="form-group">
            <label for="inputId">快递号</label>
            <input type="text" class="form-control" id="inputId">
          </div>
          <button type="button" class="btn btn-info ml10" onclick="flushTable()">条件查询</button>
        </form>
      </div>
      <div class="panel-body">
<!--        <div id="toolbar" class="btn-group">-->
<!--          <button id="btn_allot" type="button" class="btn btn-default">-->
<!--            <span class="glyphicon glyphicon-asterisk" aria-hidden="true"></span> 添加快递信息-->
<!--          </button>-->
<!--          <button id="btn_complete" type="button" class="btn btn-success">-->
<!--            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span> 修改快递信息-->
<!--          </button>-->
<!--          <button id="btn_delete" type="button" class="btn btn-danger">-->
<!--            <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 删除订单-->
<!--          </button>-->
<!--        </div>-->
        <table id="tb_order"></table>
      </div>
    </div>
  </div>
</div>

<!-- 分配订单模态框 -->
<div class="modal fade" id="allotModel" tabindex="-1" role="dialog" aria-labelledby="allotModelLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="allotModelLabel">分配订单</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal">
          <div class="form-group">
            <label for="inputCourierOption" class="col-sm-2 control-label">配送人员</label>
            <div class="col-sm-10">
              <select id="inputCourierOption" class="form-control">
                <option value=-1>未选中</option>
              </select>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="allotBtn">分配</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>
<!-- 订单详情模态框 -->
<div class="modal fade" id="infoModel" tabindex="-1" role="dialog" aria-labelledby="infoModelLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="infoModelLabel">快递详情</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal">
          <div class="form-group">
            <label for="inputInfoId" class="col-sm-2 control-label">快递号</label>
            <div class="col-sm-10">
              <p class="form-control-static" id="inputInfoId"></p>
            </div>
          </div>
          <div class="form-group">
            <label for="inputInfoName" class="col-sm-2 control-label">收件人姓名</label>
            <div class="col-sm-10">
              <p class="form-control-static" id="inputInfoName"></p>
            </div>
          </div>
          <div class="form-group">
            <label for="inputInfoTel" class="col-sm-2 control-label">联系电话</label>
            <div class="col-sm-10">
              <p class="form-control-static" id="inputInfoTel"></p>
            </div>
          </div>
          <div class="form-group">
            <label for="inputInfoAddress" class="col-sm-2 control-label">收件地址</label>
            <div class="col-sm-10">
              <p class="form-control-static" id="inputInfoAddress"></p>
            </div>
          </div>
          <div class="form-group">
            <label for="inputInfoOdd" class="col-sm-2 control-label">快递位置</label>
            <div class="col-sm-10">
              <p class="form-control-static" id="inputInfoOdd"></p>
            </div>
          </div>
          <div class="form-group">
            <label for="inputInfoRemark" class="col-sm-2 control-label">备注</label>
            <div class="col-sm-10">
              <p class="form-control-static" id="inputInfoRemark"></p>
            </div>
          </div>
          <hr>
          <hr>
          <div class="form-group">
            <label for="inputInfoOrderStatus" class="col-sm-2 control-label">快递状态</label>
            <div class="col-sm-10">
              <p class="form-control-static" id="inputInfoOrderStatus"></p>
            </div>
          </div>
          <div class="form-group">
            <label for="inputInfoCourierName" class="col-sm-2 control-label">取件方式</label>
            <div class="col-sm-10">
              <p class="form-control-static" id="inputInfoCourierName"></p>
            </div>
          </div>

        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

<script th:src="@{/assets/js/http.js}" src="../../static/assets/js/http.js"></script>
<script th:src="@{/assets/js/express.js}" src="../../static/assets/js/express.js"></script>
<script th:src="@{/assets/js/jquery.min.js}" src="../../static/assets/js/jquery.min.js"></script>
<script th:src="@{/assets/js/jquery.validate.min.js}" src="../../static/assets/js/jquery.validate.min.js"></script>
<script th:src="@{/assets/layer/layer.js}" src="../../static/assets/layer/layer.js"></script>
<script th:src="@{/assets/js/bootstrap.min.js}" src="../../static/assets/js/bootstrap.min.js"></script>
<script th:src="@{/assets/js/bootstrap-table.min.js}" src="../../static/assets/js/bootstrap-table.min.js"></script>
<script th:src="@{/assets/js/bootstrap-table-export.min.js}" src="../../static/assets/js/bootstrap-table-export.min.js"></script>
<script th:src="@{/assets/js/bootstrap-table-zh-CN.min.js}" src="../../static/assets/js/bootstrap-table-zh-CN.min.js"></script>
<script th:src="@{/assets/js/tableExport.min.js}" src="../../static/assets/js/tableExport.min.js"></script>
<script>
  $(function () {
    $("#addorder-sidebar").addClass('active');

    //1、初始化Table
    let oTable = new TableInit();
    oTable.Init();
    //2、初始化Button的点击事件
    let oButtonInit = new ButtonInit();
    oButtonInit.Init();

    // 加载快递员列表
    sendJson(HTTP.GET, "/api/v1/user/courier-list", null, true, function (res) {
      if(res.code === 0) {
        let html = '', data = res.data;
        for (let i = 0; i < data.length; i++) {
          html += '<option value="' + data[i].id + '">' + data[i].name + '</option>\n';
        }
        $("#inputCourierOption").html(html);
      } else {
        layer.msg(res.msg, {icon: 2});
      }
    }, function () {
      layer.msg("未知错误",{icon:2});
    });
  });

  var TableInit = function () {
    let oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
      $('#tb_order').bootstrapTable({
        url: '/api/v1/order/list',          //请求后台的URL（*）
        method: HTTP.GET,                   //请求方式（*）
        toolbar: '#toolbar',                //工具按钮组id
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: false,                    //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: oTableInit.queryParams,//传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber:1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端。后台分页时意义不大
        showColumns: true,                  //是否显示所有的列
        showRefresh: true,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        // height: 750,                     //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
        uniqueId: "id",                     //每一行的唯一标识，一般为主键列
        showToggle:false,                   //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,                  //是否显示父子表
        showExport: false,                   //是否显示导出
        exportDataType: "basic",            //导出的模式是当前页basic、所有数据all、选中数据selected。
        columns: [{
          checkbox: true
        },{
          field: 'odd',
          title: '快递单号'
        }, {
          field: 'recName',
          title: '收件人'
        }, {
          field: 'recTel',
          title: '收件人电话'
        }, {
          field: 'address',
          title: '快递寄达地址'
        }, {
          field: 'recAddress',
          title: '快递位置'
        }, {
          field: 'remark',
          title: '快递备注'
        }, {
            field: 'orderStatus',
            title: '快递状态',
            formatter: orderFormatter
          }, {
            field: 'createDate',
            title: '入库时间'
          },{
          field: 'courierRemark',
          title: '取件方式'
        }, {
            field: 'id',
            title: '操作',
            align: 'center',
            valign: 'middle',
            formatter: actionFormatter
          }]
      });
    };

    // 传递给后台的参数
    oTableInit.queryParams = function (params) {
      return {   //这里的键的名字和后台参数必须一致
        size: params.limit,                             //页面大小
        current: (params.offset / params.limit) + 1,   //页码
        type: 0,
        // 筛选参数
        id: $("#inputId").val(),
        status: $("#inputOrderStatus").val(),
        payment: $("#inputPaymentStatus").val(),
        startDate: $("#inputStartDate").val(),
        endDate:$("#inputEndDate").val(),
      };
    };
    return oTableInit;
  };

  var ButtonInit = function () {
    let oInit = new Object();

    oInit.Init = function () {
      // 订单分配
      $("#btn_allot").click(function () {
        let row = $('#tb_order').bootstrapTable("getSelections");
        if (row.length > 0) {
          let ids = new Array();
          for (let i = 0; i < row.length; i++) {
            if (row[i].orderStatus === 1 ) {
              ids.push(row[i].id);
            }
          }
          if (ids.length === 0) {
            layer.msg("选中的没有可分配的订单", {icon: 7});
          } else {
            $("#allotModel").modal("show");

            // 点击模态框分配按钮后
            $("#allotBtn").click(function () {
              $("#allotModel").modal("hide");
              let courier = $("#inputCourierOption").val();
              sendArray(HTTP.POST, "/api/v1/order/batch-allot", {
                "ids": ids,
                "courier": courier
              }, false, function (res) {
                if (res.code === 0) {
                  layer.msg("分配成功" + res.data.success + "个，失败" + res.data.error + "个", {icon: 1});
                  flushTable();
                } else {
                  layer.msg(res.msg, {icon: 2});
                }
              }, function () {
                layer.msg("未知错误", {icon: 2});
              });
            });
          }
        } else {
          layer.msg("请先选中订单", {icon: 7});
        }
      });
      // 完成订单
      $("#btn_complete").click(function () {
        var row = $('#tb_order').bootstrapTable("getSelections");
        if (row.length > 0) {
          var ids = new Array();
          for (var i = 0; i < row.length; i++) {
            if (row[i].orderStatus === 2 || row[i].orderStatus === 4) {
              ids.push(row[i].id);
            }
          }
          if (ids.length === 0) {
            layer.msg("选中的没有可完成的订单", {icon: 7});
            return false;
          } else {
            layer.confirm("即将处理订单：" + ids + "，确认执行？", {
              btn: ['确定', '取消']
            }, function () {
              layer.prompt({title: "成功信息", formType: 2}, function (val, index) {
                sendArray(HTTP.POST, "/api/v1/order/batch-complete", {
                  "ids": ids,
                  "remark": val
                }, false, function (res) {
                  if (res.code === 0) {
                    layer.msg("成功，处理" + res.data.success + "个，失败" + res.data.error + "个", {icon: 1});
                    layer.close(index);
                    flushTable();
                  } else {
                    layer.msg(res.msg, {icon: 2});
                  }
                }, function () {
                  layer.msg("未知错误", {icon: 2});
                });
              });
            }, function () {
            });
          }
        } else {
          layer.msg("请先选中订单", {icon: 7});
        }
      });
      // 异常订单
      $("#btn_error").click(function () {
        let row = $('#tb_order').bootstrapTable("getSelections");
        if (row.length > 0) {
          let ids = new Array();
          for (let i = 0; i < row.length; i++) {
            if (row[i].orderStatus === 2) {
              ids.push(row[i].id);
            }
          }
          if (ids.length === 0) {
            layer.msg("选中的没有可异常的订单", {icon: 7});
            return false;
          } else {
            layer.confirm("即将异常订单：" + ids + "，确认执行？", {
              btn: ['确定', '取消']
            }, function () {
              layer.prompt({title: "异常信息", formType: 2}, function (val, index) {
                sendArray(HTTP.POST, "/api/v1/order/batch-error", {
                  "ids": ids,
                  "remark": val
                }, false, function (res) {
                  if (res.code === 0) {
                    layer.msg("成功，处理" + res.data.success + "个，失败" + res.data.error + "个", {icon: 1});
                    layer.close(index);
                    flushTable();
                  } else {
                    layer.msg(res.msg, {icon: 2});
                  }
                }, function () {
                  layer.msg("未知错误", {icon: 2});
                });
              });
            }, function () {
            });
          }
        } else {
          layer.msg("请先选中订单", {icon: 7});
        }
      });
      // 删除订单
      $("#btn_delete").click(function () {
        let row = $('#tb_order').bootstrapTable("getSelections");
        if(row.length > 0) {
          let ids = new Array();
          for (let i = 0; i < row.length; i++) {
            if (row[i].orderStatus !== 2) {
              ids.push(row[i].id);
            }
          }
          if (ids.length === 0) {
            layer.msg("选中项不包含可删除的订单",{icon:0});
            return false;
          } else {
            layer.confirm("删除的订单号为：" + ids + "，确认执行？", {
              btn: ['确定','取消']
            }, function(){
              sendArray(HTTP.POST, "/api/v1/order/batch-remove", {"ids": ids}, false, function (res) {
                if(res.code === 0) {
                  layer.msg("成功，删除" + res.data.success + "个，失败" + res.data.error + "个",{icon:1});
                  flushTable();
                }
              }, function () {
                layer.msg("未知错误",{icon:2});
              });
            }, function(){
            });
          }
        }
      });
    };
    return oInit;
  };

  //操作栏的格式化
  function actionFormatter(value, row, index) {
    let id = "'" + value + "'";
    return '<button class="btn btn-xs btn-info" onclick="showDetail('+id+')" title="查看"><span class="glyphicon glyphicon-search"></span></button>\n';
  }
  // 订单状态的格式化
  function orderFormatter(value, row, index) {
    if(value === 4)
      return '<span style="color:red">订单异常</span>';
    else if (value === 3)
      return '<span style="color:olivedrab">订单完成</span>';
    else if (value === 2)
      return '<span style="color:#42afff">派送中</span>';
    else if (value === 1)
      return '<span style="color:grey">等待接单</span>';
  }
  // 支付状态格式化
  function paymentFormatter(value, row, index) {
    if(value === 1)
      return '<span style="color:#f5a623">等待支付</span>';
    else if (value === 2)
      return '<span style="color:red">支付关闭</span>';
    else if (value === 3)
      return '<span style="color:green">支付成功</span>';
    else if (value === 4)
      return '<span style="color:grey">支付结束</span>';
  }

  function flushTable() {
    $("#tb_order").bootstrapTable('refresh',{url : '/api/v1/order/list'} );
  }

  function showDetail(id) {
    sendJson(HTTP.GET, "/api/v1/order/" + id, null, false, function (res) {
      if (res.code !== 0) {
        layer.msg(res.msg, {icon: 2});
      } else {
        // 初始化模态框信息
        let data = res.data;
        $("#inputInfoId").text(data.orderId);
        $("#inputInfoName").text(data.recName);
        $("#inputInfoTel").text(data.recTel);
        $("#inputInfoAddress").text(data.recAddress);
        $("#inputInfoOdd").text(data.odd);
        $("#inputInfoCompany").text(data.companyName);
        $("#inputInfoRemark").text(data.remark);

        $("#inputInfoPaymentType").text(data.paymentType);
        $("#inputInfoPaymentId").text(data.paymentId);
        $("#inputInfoMoney").text(data.payment);
        $("#inputInfoPaymentStatus").text(data.paymentStatus);

        $("#inputInfoOrderStatus").text(data.orderStatus);
        $("#inputInfoCourierName").text(data.courierFrontName);
        $("#inputInfoCourierRemark").text(data.courierRemark);

        $("#infoModel").modal("show");
      }
    }, function () {
      layer.msg("未知错误", {icon: 2});
    });
  }

</script>
</body>
</html>
